package gdingtalk

import (
	"crypto/sha1"
	"errors"
	"fmt"
	"gitee.com/zjlsliupei/ghelp"
	"github.com/rs/xid"
	"strconv"
	"strings"
	"time"
)

type Auth struct {
}

func NewAuth() Auth {
	return Auth{}
}

// GetAuthScopes 获取企业授权信息
func (a *Auth) GetAuthScopes(corpId string) Response {
	return Get().
		AutoAccessToken(corpId).
		SetPath("/auth/scopes").
		Do()
}

// GetAuthInfo 生成dd.config需要的授权信息
func (a *Auth) GetAuthInfo(corpId, urlStr string) (ghelp.MAP, error) {
	agentId, err := gDingTalk.GetAgentId(corpId)
	if err != nil {
		return ghelp.MAP{}, err
	}
	timestamp := time.Now().Unix()
	nonceStr := xid.New().String()
	arr := strings.Split(urlStr, "#")
	var url string
	if len(arr) > 0 {
		url = arr[0]
	}
	// 计算签名
	ticket, err := a.GetCorpJsTicket(corpId)
	if err != nil {
		return ghelp.MAP{}, err
	}
	plain := `jsapi_ticket=` + ticket +
		`&noncestr=` + nonceStr +
		`&timestamp=` + strconv.FormatInt(timestamp, 10) +
		`&url=` + url
	h := sha1.New()
	h.Write([]byte(plain))
	sign := fmt.Sprintf("%x", h.Sum(nil))
	return ghelp.MAP{
		"corpId":    corpId,
		"timestamp": timestamp,
		"nonceStr":  nonceStr,
		"url":       url,
		"agentId":   agentId,
		"signature": sign,
	}, nil
}

// GetCorpJsTicket 获取企业js_ticket,并会自动缓存
func (a *Auth) GetCorpJsTicket(corpId string) (string, error) {
	jsTicketKey := "js_ticket_" + corpId
	if jsTicket, _ := gCache.cGet(jsTicketKey); jsTicket != "" {
		return jsTicket, nil
	}
	res := Get().SetPath("/get_jsapi_ticket").AutoAccessToken(corpId).Do()
	if res.IsSuccess() {
		jsTicket := res.GetBody("ticket").String()
		gCache.cPut(jsTicketKey, jsTicket, res.GetBody("expires_in").Int()-200)
		return jsTicket, nil
	} else {
		return "", errors.New(res.GetErrmsg())
	}
}
